<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>WebSocket Test</title>

  <link rel="stylesheet" href="https://cdn.bootcss.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
  <script src="https://cdn.bootcss.com/jquery/3.2.1/jquery.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
  <script src="https://cdn.bootcss.com/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
  <script src="https://cdn.bootcss.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
  <script src="https://cdn.bootcss.com/pako/1.0.10/pako_deflate.js"></script>
  <script src="https://cdn.bootcss.com/pako/1.0.10/pako_inflate.js"></script>
</head>
<body>


<div class="container-fluid">

  <div class="row">
    <div class="col-2" style="border: 1px">


      <br>

      <div class="form-group">
        <label for="websocket_url">WebSocket URL</label>
        <input type="text" class="form-control" id="websocket_url" value="api.huobipro.com">
      </div>

      <div class="form-group">
        <label for="websocket_type">WebSocket Type</label>
        <input type="text" class="form-control" id="websocket_type" value="sub">
      </div>

      <div class="form-group">
        <label for="websocket_topic">Topic</label>
        <input type="text" class="form-control" id="websocket_topic" placeholder="Topic">
      </div>

      <button type="button" class="btn btn-primary" id="executeBtn">执行</button>
      <button type="button" class="btn btn-secondary" id="closeBtn">关闭</button>


    </div>
    <div class="col-10">

      <label for="receiveMessage">Message</label>
      <textarea class="form-control" id="receiveMessage" rows="20"></textarea>

    </div>
  </div>
</div>


</body>

<script>
  var gunzip_message = true;

  var socket;

  $("#executeBtn").click(function(){

    var url = $("#websocket_url").val();
    var type =$("#websocket_type").val();
    var topic =$("#websocket_topic").val();

    if (socket == null) {
      start_ws(topic,type,url);
    } else {
      sendTopic(type,topic);
    }
  });

  $("#closeBtn").click(function(){
    if (socket != null) {
      socket.close();
    }
    socket = null;
  });



  function sendTopic(ws_type,topic,onlySend) {
    /* sub topic "market.$symbol.depth.percent10" */
    var str = topic;
    if (!onlySend) {
      if(ws_type == 'sub'){
        str = JSON.stringify({'sub': topic, 'id': new Date().getTime()});

      }else {
        str = JSON.stringify({'req': topic, 'id': new Date().getTime()});
      }
    }
    document.getElementById('receiveMessage').innerHTML = '发送数据：'+str+'\n';
    socket.send(str);
  }



  function start_ws(topic,ws_type,url) {

    var requestUrl = "wss://"+url+"/ws";
    socket = new WebSocket(requestUrl);

    socket.binaryType = 'arraybuffer';
    socket.onopen = function (event) {
      /* sub topic "market.$symbol.depth.percent10" */
      if(ws_type == 'sub'){
        str = JSON.stringify({'sub': topic, 'id': new Date().getTime()});

      }else {
        str = JSON.stringify({'req': topic, 'id': new Date().getTime()});
      }
      sendTopic(ws_type,str,true);
    };

    socket.onmessage = function (event) {
      var raw_data = event.data;
      var json = gunzip_message ? pako.inflate(new Uint8Array(raw_data), {to: 'string'}) : raw_data;
      var data = JSON.parse(json);

      if(json.indexOf('debug session') < 0){
        var data_json = document.getElementById('receiveMessage').value;
        document.getElementById('receiveMessage').innerHTML = data_json + '收到数据：'+json+'\n';
      }


      /* deal with server heartbeat */
      if (data['ping']) {
        console.log('WebSocket receive ping and return pong at time: ' + new Date());
        socket.send(JSON.stringify({'pong': data['ping']}));
      }
    };

    socket.onclose = function(event) {
      //console.log('WebSocket close at time: ' + new Date());
      var data_json = document.getElementById('returnData').value;
      document.getElementById('receiveMessage').innerHTML = data_json + 'socket is close.\n'
    };

    socket.onerror = function (ev) {
      socket = null;
    }
  }

</script>
</html>